<template>
  <div class="details_box">
    <div class="btns add_btn_top">
      <el-button type="primary"
                 icon="el-icon-edit-outline"
                 size="mini"
                 class="add_btn"
                 @click="handEdit">编辑</el-button>
      <el-button icon="el-icon-delete"
                 size="mini"
                 class="add_btn"
                 @click="handDel()"
                 v-permission="[25, 'button']">删除</el-button>
      <el-button icon="el-icon-close"
                 size="mini"
                 class="add_btn"
                 @click="handBack">关闭</el-button>
    </div>
    <Details :detail="detail"
             :qrCode="qrCode"></Details>
    <div style="background: #fff; margin-top: 10px">
      <Mytitle title="网关"></Mytitle>
      <!-- <TabPages ref="tabListRef" :isBtn="false"></TabPages> -->
      <div class="gateway"
           v-permission="[4, 'list']">
        <el-table height="100px"
                  v-adaptive
                  :data="tableData"
                  style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left"
                       inline
                       class="demo-table-expand">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="元数据 :">
                      <span>{{ props.row.metaCount }}项</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="ID :">
                      <span>{{ props.row._id }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="子网掩码 :">
                      <span>{{ props.row.subnet_mask }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="MAC地址 :">
                      <span>{{ props.row.mac_address }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="网关地址 :">
                      <span>{{ props.row.gateway_address }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="创建时间 :">
                      <span>{{ props.row.crdt | formatDate }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column prop="date"
                           label="图像"
                           align="left">
            <template slot-scope="{ row: { imgu } }">
              <img style="width: 40px; height: 40px"
                   :src="imgu | filtersFileUrl()" />
            </template>
          </el-table-column>
          <el-table-column label="品牌"
                           prop="brand"
                           align="left">
          </el-table-column>
          <el-table-column label="型号"
                           prop="model"
                           align="left">
          </el-table-column>
          <el-table-column label="IP地址"
                           prop="ip"
                           align="left">
          </el-table-column>
          <el-table-column label="名称"
                           prop="name"
                           align="left">
          </el-table-column>
          <el-table-column label="网关Token"
                           prop="tokn"
                           align="left">
          </el-table-column>
          <el-table-column label="操作"
                           width="100"
                           align="center">
            <template slot-scope="{ row: { tokn } }">
              <span style="color: #2680d2; font-size: 16px; margin-right: 10px"
                    class="el-icon-edit-outline"
                    @click="handEditNet(tokn)"></span>
              <!-- v-permission="[2, 'icon']" -->
              <span v-permission="[2, 'icon']"
                    style="color: #2680d2; font-size: 16px"
                    class="el-icon-delete"
                    @click="handDelTab(tokn)"></span>
            </template>
          </el-table-column>
        </el-table>
        <Pagination @pagination="pagination"
                    :total="total"
                    :page.sync="pageNum"
                    :limit.sync="pageSize"
                    :pageSizes.sync="pageSizes" />
      </div>
    </div>
    <AddDialog ref="addDialgRef"
               :typeList="typeList"
               :showDialog="addFlag"
               @closeDialog="closeDialog"
               :editmetaData="editmetaData"
               :isedit="isedit"
               :token="assetTypeToken"></AddDialog>
    <NetWorkAddDialog ref="addNetDialgRef"
                      :typeList="typeListNet"
                      :showDialog.sync="addFlagNet"
                      @closeDialog="closeDialogNet"
                      :editmetaData="editmetaDataNet"
                      :isedit="true"
                      :token="tokenNet"></NetWorkAddDialog>
  </div>
</template>

<script>
import Details from "./components/Details";
import {
  getAssettypesDetail,
  getAssettypes,
  getAssetsDetails
} from "@/api/assets";
import AddDialog from "./components/AddDialog.vue";
import NetWorkAddDialog from "../network/components/AddDialog.vue";
import Mytitle from "@/components/MyTitle";
import { paginationMixins } from "@/mixin/pagination";
import { getAssetGateway } from "@/api/gateway";
import { delAssetsType, getQrCode } from "@/api/assetsType";
import { delAssets } from "@/api/assets";
export default {
  mixins: [paginationMixins],
  components: {
    NetWorkAddDialog,
    Details,
    AddDialog,
    Mytitle
  },
  data() {
    return {
      typeList: [
        {
          token: "Device",
          name: "设备"
        }
      ],
      typeListNet: [],
      detail: {},
      qrCode: "",
      assetTypeToken: "",
      editmetaData: {},
      editmetaDataNet: {},
      isedit: false,
      token: "",
      addFlag: false,
      addFlagNet: false,
      tableData: [],
      tokenNet: ""
    };
  },
  mounted() {
    this.assetTypeToken = this.$route.query.assetTypeToken;
    this.init();

    this.$nextTick(() => {
      // this.$refs.tabListRef.assetTypeToken = this.assetTypeToken;
      // this.$refs.tabListRef.init(this.assetTypeToken);
    });
    // this.getQrCode();
  },
  methods: {
    async handEditNet(assetToken) {
      // 先获取到网关类型
      const resType = await getAssettypes({ page: 1, pageSize: 0 });
      const { data: dataType } = resType;
      this.typeListNet = dataType.results;
      getAssetsDetails(assetToken).then(res => {
        const { data } = res;
        this.$nextTick(() => {
          this.$refs.addNetDialgRef.deviceGroupForm = data;
          // 编辑弹窗ip格式
          let ipData = [];
          let ipArray = [];
          let gatewayAddressData = [];
          let gatewayAddressArray = [];
          if (!data.gatewayAddress) {
            gatewayAddressArray = [
              {
                value: ""
              },
              {
                value: ""
              },
              {
                value: ""
              },
              {
                value: ""
              }
            ];
          } else {
            gatewayAddressData = data.gatewayAddress.split(".");
            gatewayAddressData.forEach(arg => {
              gatewayAddressArray.push({
                value: arg
              });
            });
          }
          if (!data.ip) {
            ipArray = [
              {
                value: ""
              },
              {
                value: ""
              },
              {
                value: ""
              },
              {
                value: ""
              }
            ];
          } else {
            ipData = data.ip.split(".");
            ipData.forEach(arg => {
              ipArray.push({
                value: arg
              });
            });
          }
          let subnetMaskData = [];
          let subnetMaskArray = [];
          this.$refs.addNetDialgRef.deviceGroupForm.ip = ipArray;
          this.$refs.addNetDialgRef.deviceGroupForm.gatewayAddress = gatewayAddressArray;
          // 编辑弹窗子网掩码格式
          if (!data.subnetMask) {
            subnetMaskArray = [
              {
                value: ""
              },
              {
                value: ""
              },
              {
                value: ""
              },
              {
                value: ""
              }
            ];
          } else {
            subnetMaskData = data.subnetMask.split(".");
            subnetMaskData.forEach(item => {
              subnetMaskArray.push({
                value: item
              });
            });
          }
          this.$refs.addNetDialgRef.deviceGroupForm.SubnetAdress = subnetMaskArray;
          this.editmetaDataNet = data.metadata;
          // 此处传递的是老的token 需要深拷贝
          this.tokenNet = _.cloneDeep(data.token);
          this.$refs.addNetDialgRef.deviceGroupForm.assetTypeToken =
            data.assetType.token;
        });
      });
      this.addFlagNet = true;
    },
    async initTab(token) {
      // var tenantToken = "";
      // if (_.isString(this.$store.getters.tenant)) {
      //   tenantToken = JSON.parse(this.$store.getters.tenant).token;
      // } else {
      //   tenantToken = this.$store.getters.tenant.token;
      // }
      const res = await getAssetGateway({
        // tenantToken,
        page: this.pageNum,
        pageSize: this.pageSize,
        // name: this.searchName,
        // ip: this.searchIp,
        atIds: [this.detail.id]
      });
      console.log("1 :>> ", res);
      const { status, data } = res;
      if (status === 200) {
        const { data: results, sum } = data.data;
        this.total = sum;
        this.tableData = results;
      }
    },
    handBack() {
      this.$router.push({
        path: "/networkType"
      });
    },
    handDel(assetToken) {
      var that = this;
      if (this.tableData && this.tableData.length !== 0) {
        // this.$msg("该类型下有网关,不可删除!");
        this.$msg({
          message: "该类型下有网关,不可删除!",
          type: "error"
        });
        return;
      }
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delAssetsType(this.assetTypeToken).then(res => {
          this.$msg({
            type: "success",
            message: "删除成功!"
          });
          this.handBack();
        });
      });
    },
    closeDialogNet() {
      this.initTab();
    },
    toLink(token) {
      // this.$router.go(0);
      this.$router.push({
        path: "/_empty",
        query: {
          data: JSON.stringify({ assetTypeToken: token }),
          path: "networkTypDetails"
        }
      });
    },
    closeDialog(isRefresh, token) {
      // isRefresh是否刷新
      if (isRefresh) {
        if (token) {
          this.assetTypeToken = token;
          this.toLink(token);
          // this.$router.push({
          //   name: "networkTypDetails",
          //   query: {
          //     assetTypeToken: token,
          //   },
          // });
        } else {
          this.init();
        }
      }
      this.addFlag = false;
    },
    handDelTab(assetToken) {
      var that = this;
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delAssets(assetToken).then(res => {
          this.$msg({
            type: "success",
            message: "删除成功!"
          });
          this.initTab();
        });
      });
    },
    init() {
      getAssettypesDetail(this.assetTypeToken).then(res => {
        const { data } = res;
        this.detail = data;
        // 获取类型下边的网关
        this.initTab();
      });
    },
    handEdit() {
      this.addFlag = true;
      this.$nextTick(() => {
        this.$refs.addDialgRef.deviceGroupForm = this.detail;
        this.isedit = true;
        this.editmetaData = this.detail.metadata;
        // 此处传递的是老的token 需要深拷贝
        // this.token = this.assetTypeToken;
        this.$refs.addDialgRef.deviceGroupForm.assetTypeToken = this.assetTypeToken;
        // this.$refs.addDialgRef.metaDataJson = data.metadata;
      });
    },
    getQrCode() {
      var param = { responseType: "arraybuffer" };
      getQrCode(param, this.assetTypeToken).then(res => {
        this.qrCode =
          "data:image/png;base64," +
          btoa(
            new Uint8Array(res.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ""
            )
          );
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.details_box {
  position: relative;
  /deep/ .el-form-item {
    margin-bottom: 10px;
  }
  .btns {
    position: absolute;
    right: 0;
    top: -40px;
    z-index: 22;
  }
}
.tab_box {
  margin-top: 10px;

  background-color: #fff;
  .tab_height {
  }
}
</style>
